<template>
  <div>
    <van-cell
      :title="label"
      :value="dateTime ? dateTime : placeholder"
      @click="show = true"
    />
    <van-calendar
       v-if="componentProps.type"
       ref="calendar"
      :type="componentProps.type"
      :allow-same-day="componentProps.allowSameDay"
      v-model:show="show"
      @open="open"
      @confirm="onConfirm"
    />
    <van-calendar
      v-else
      ref="calendar"
      v-model:show="show"
      @open="open"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
import dayjs from "dayjs"
import { Calendar as VanCalendar, Cell as VanCell } from "vant";
const formatDate = (date) =>
  `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;

export default {
  name: "CommonCalendar",
  components: { VanCalendar, VanCell },
  props: {
    label: {
      type: String,
      default: "",
    },
    componentProps: {
      type: Object,
      default: ()=>{},
    },
    placeholder: {
      type: String,
      default: "",
    },
    modelValue: {},
  },
  data() {
    return {
      dateTime: "",
      show: false,
    };
  },
  watch: {
    modelValue: {
      // 数据变化时执行的逻辑代码
      handler(newValue, oldValue) {
        if (newValue&&newValue.length==0) {
          this.dateTime = "";
          this.$refs.calendar.reset();
        }
      },
      // 开启深度监听
      deep: true,
    },
  },
  methods: {
    open() {},
    onConfirm(values) {
      if(this.componentProps.type=='range'){
        const [start, end] = values;
         this.$emit("update:modelValue", values);
         this.dateTime = `${formatDate(start)} - ${formatDate(end)}`;
      }else{
         this.$emit("update:modelValue",  dayjs(values).format(this.componentProps.valueFormat || 'YYYY-MM-DD'));
         this.dateTime = dayjs(values).format(this.componentProps.valueFormat || 'YYYY-MM-DD');
      }
      this.show = false;
    },
  },
};
</script>